package cn.com.dstz.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
  
/**
 * 该类主要针对数据列表的分页处理
 * @author 叶装装
 *
 */
public class Pagination{
	
	/**
	 * 获取统计的SQL语句
	 * @param SQL
	 * @return
	 */
	public static String getCountSQL( String SQL ){
		if( StringUtils.isBlank( SQL )){
			return null;
		}
		int fromIndex = SQL.indexOf( "from" );
		
		String afterFrom =  SQL.substring( fromIndex, SQL.length( ) );
		
		int groupByIndex = afterFrom.lastIndexOf( "group by" );
		
		if( groupByIndex != -1 ){
			afterFrom = afterFrom.substring( 0, groupByIndex );
		}
		
		
		return "select count(*) as a " + afterFrom;
		
		// 
	}
	/**
	 * 获取统计的HQL
	 * @param HQL		要查询的HQL
	 * @return
	 */
	public static String getCountHQL( String HQL ){
		
		if( StringUtils.isBlank( HQL ) ){
			return null;
		}
		
		return " select count(*) " + HQL;
	}
	
	public static Map< String, Object >  reflect( Object obj ){
		Field[] fields = obj.getClass( ).getDeclaredFields();
		Map< String, Object > dataMap = new HashMap< String, Object >( );
		
		for( Field field : fields ){
			try{
				Method m = obj.getClass( ).getMethod( "get" + getMethodName(field.getName()));
				Object value = m.invoke(obj );
				dataMap.put( field.getName( ), value );
			}catch( Exception e ){
				e.printStackTrace();
				return null;
			}
		}
		
		return dataMap;
	}
	
	public static  String getMethodName(String fildeName) throws Exception{
		  byte[] items = fildeName.getBytes();
		  items[0] = (byte) ((char) items[0] - 'a' + 'A');
		  return new String(items);
	}
	
	/**
	 * 转换long 为 int
	 * @param value
	 * @return
	 */
	public static int convertLongToInt( Long value ){
		if( value == null ){
			return 0;
		}
		
		if( value > Integer.MAX_VALUE ){
			return Integer.MAX_VALUE;
		}
		
		return value.intValue( );
	}
	
	
	public static String processQueryParam( String param ){
		int pointIndex = param.lastIndexOf( "." );
		if( pointIndex == -1 ){
			return param;
		}
		return param.substring( pointIndex + 1, param.length( )  );
	}
	
	public static void main( String [ ] args ) {
		String SQL = " SELECT *  from abceeeee group by a";
		System.out.println( getCountSQL( SQL ) );
		
	}
}
